package com.ra.filter;

import com.ra.service.JwtTokenService;
import com.ra.service.impl.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import org.springframework.security.core.context.SecurityContextHolder;


import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.ra.constant.AuthConstant.*;

/**
 * Author : 今晚几点睡_Ada
 * Date: 2023/3/9
 * Time: 13:55
 * 注: Jwt登录授权过滤器
 */

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private UserDetailServiceImpl userDetailService;

    @Resource
    private JwtTokenService jwtTokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader(TOKEN_HEADER);
        if (authHeader!=null&&authHeader.startsWith(TOKEN_HEAD)){
            String authToken = authHeader.substring(TOKEN_HEAD.length());
            String username = jwtTokenService.getUserNameFormToken(authToken);
            if (username!=null&& SecurityContextHolder.getContext().getAuthentication()==null){
                //登录
                UserDetails userDetails = userDetailService.loadUserByUsername(username);
                //验证token是否有效，重新设置用户对象
                if (jwtTokenService.validateToken(authToken,userDetails)){
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }

            }

        }
        chain.doFilter(request,response);
    }
}
